<template>
  <view class="forecast-chart">
    <canvas 
      :canvas-id="chartId" 
      :id="chartId"
      class="chart-canvas"
      :style="{ width: chartWidth + 'px', height: chartHeight + 'px' }"
    ></canvas>
  </view>
</template>

<script>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'ForecastChart',
  props: {
    timeSeries: {
      type: Array,
      required: true
    },
    readOnly: {
      type: Boolean,
      default: true
    },
    chartId: {
      type: String,
      default: () => 'chart_' + Date.now() + '_' + Math.random().toString(36).slice(2, 9)
    }
  },
  setup(props) {
    const chartWidth = ref(800)
    const chartHeight = ref(350)
    let chartInstance = null

    const initChart = () => {
      try {
        console.log('🎨 [ForecastChart] 初始化图表:', props.chartId)
        console.log('   timeSeries长度:', props.timeSeries?.length)
        
        const canvas = document.getElementById(props.chartId)
        if (!canvas) {
          console.error('❌ Canvas not found:', props.chartId)
          return
        }
        
        console.log('✅ Canvas找到:', canvas)
        console.log('   Canvas尺寸:', canvas.clientWidth, 'x', canvas.clientHeight)
        
        if (canvas.clientWidth === 0 || canvas.clientHeight === 0) {
          console.error('❌ Canvas尺寸为0，延迟重试')
          setTimeout(() => initChart(), 200)
          return
        }

        if (chartInstance) {
          chartInstance.dispose()
          chartInstance = null
        }

        chartInstance = echarts.init(canvas)
        console.log('✅ ECharts实例创建成功')

        const timeData = props.timeSeries.map(item => item.time)
        const rainData = props.timeSeries.map(item => item.rain || 0)
        const qSimData = props.timeSeries.map(item => item.QSim || 0)
        const runoffData = props.timeSeries.map(item => item.runoffSim || 0)

        const option = {
          backgroundColor: '#ffffff',
          title: {
            text: '预报结果',
            left: 'center',
            textStyle: {
              color: '#262626',
              fontSize: 16,
              fontWeight: 600
            }
          },
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0, 0, 0, 0.85)',
            borderColor: '#1890ff',
            borderWidth: 1,
            textStyle: {
              color: '#fff'
            }
          },
          toolbox: {
          feature: {
            myFull: {
              // 全屏
              show: true,
              title: '全屏',
              icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
              onclick: (e) => {
                // let fullFlag = true;
                let element = document.getElementById(props.chartId);
                // 一些浏览器的兼容性
                if (element.requestFullScreen) {
                  // HTML W3C 提议
                  element.requestFullScreen();
                } else if (element.msRequestFullscreen) {
                  // IE11
                  element.msRequestFullScreen();
                } else if (element.webkitRequestFullScreen) {
                  // Webkit (works in Safari5.1 and Chrome 15)
                  element.webkitRequestFullScreen();
                } else if (element.mozRequestFullScreen) {
                  // Firefox (works in nightly)
                  element.mozRequestFullScreen();
                }
                // 退出全屏
                if (element.requestFullScreen) {
                  document.exitFullscreen();
                } else if (element.msRequestFullScreen) {
                  document.msExitFullscreen();
                } else if (element.webkitRequestFullScreen) {
                  document.webkitCancelFullScreen();
                } else if (element.mozRequestFullScreen) {
                  document.mozCancelFullScreen();
                }
              },
            },
          },
        },
          legend: {
            data: ['降雨', '模拟流量', '径流'],
            top: 35,
            textStyle: {
              color: '#262626',
              fontSize: 12
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            top: '20%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: timeData,
            axisLabel: {
              color: '#595959',
              rotate: 45,
              fontSize: 10
            },
            axisLine: {
              lineStyle: {
                color: '#d9d9d9'
              }
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '流量(m³/s)',
              position: 'left',
              nameTextStyle: {
                color: '#262626',
                fontSize: 12
              },
              axisLabel: {
                color: '#595959',
                fontSize: 11
              },
              axisLine: {
                lineStyle: {
                  color: '#d9d9d9'
                }
              },
              splitLine: {
                lineStyle: {
                  color: '#f0f0f0'
                }
              }
            },
            {
              type: 'value',
              name: '降雨(mm)',
              position: 'right',
              inverse: true,
              nameTextStyle: {
                color: '#262626',
                fontSize: 12
              },
              axisLabel: {
                color: '#595959',
                fontSize: 11
              },
              axisLine: {
                lineStyle: {
                  color: '#d9d9d9'
                }
              },
              splitLine: {
                show: false
              }
            }
          ],
          series: [
            {
              name: '降雨',
              type: 'bar',
              yAxisIndex: 1,
              data: rainData,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(59, 130, 246, 0.8)' },
                  { offset: 1, color: 'rgba(59, 130, 246, 0.3)' }
                ])
              }
            },
            {
              name: '模拟流量',
              type: 'line',
              data: qSimData,
              smooth: true,
              lineStyle: {
                color: '#667eea',
                width: 3
              },
              itemStyle: {
                color: '#667eea'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(102, 126, 234, 0.3)' },
                  { offset: 1, color: 'rgba(102, 126, 234, 0.05)' }
                ])
              }
            },
            {
              name: '径流',
              type: 'line',
              data: runoffData,
              smooth: true,
              lineStyle: {
                color: '#f59e0b',
                width: 2,
                type: 'dashed'
              },
              itemStyle: {
                color: '#f59e0b'
              }
            }
          ]
        }

        chartInstance.setOption(option)
        console.log('✅✅✅ 图表渲染成功:', props.chartId)
      } catch (error) {
        console.error('❌ Chart initialization error:', error)
      }
    }

    // 处理窗口大小变化
    const handleResize = () => {
      if (chartInstance) {
        nextTick(() => {
        chartInstance.resize()
        })
      }
    }

    // ResizeObserver 监听容器大小变化
    let resizeObserver = null

    onMounted(() => {
      console.log('🎬 [ForecastChart] 组件挂载:', props.chartId)
      setTimeout(() => {
        initChart()
      }, 300)
      
      // 添加 resize 监听
      window.addEventListener('resize', handleResize)
      
      // 使用 ResizeObserver 监听canvas容器的大小变化
      const canvas = document.getElementById(props.chartId)
      if (canvas && canvas.parentElement && window.ResizeObserver) {
        resizeObserver = new ResizeObserver(() => {
          handleResize()
        })
        resizeObserver.observe(canvas.parentElement)
      }
    })

    onUnmounted(() => {
      // 清理 resize 监听
      window.removeEventListener('resize', handleResize)
      
      if (resizeObserver) {
        resizeObserver.disconnect()
        resizeObserver = null
      }
      
      // 销毁图表实例
      if (chartInstance) {
        chartInstance.dispose()
        chartInstance = null
      }
    })

    watch(() => props.timeSeries, () => {
      if (chartInstance) {
        initChart()
      }
    }, { deep: true })

    return {
      chartWidth,
      chartHeight,
      chartId: props.chartId
    }
  }
}
</script>

<style scoped>
.forecast-chart {
  width: 100%;
  min-height: 400px;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart-canvas {
  width: 100% !important;
  height: 100% !important;
  display: block;
}
</style>

